package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.*;
import com.itheima.domain.vo.ExportProductVo;
import com.itheima.domain.vo.ExportResult;
import com.itheima.domain.vo.ExportVo;
import com.itheima.service.cargo.ContractService;
import com.itheima.service.cargo.ExportProductService;
import com.itheima.service.cargo.ExportService;
import com.itheima.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/export")
@Slf4j
public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    //合同管理列表
    @RequestMapping("/contractList")
    public String contractList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize) {
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        //查询条件：状态为2 (已审核)
        criteria.andStateEqualTo(2);
        PageInfo<Contract> pageInfo = contractService.findByPage(example, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/export/export-contractList";
    }

    //出口报运列表
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行报运单列表分页的方法");
        ExportExample exportExample = new ExportExample();
        //按创建时间排序，降序
        exportExample.setOrderByClause("create_time desc");
        ExportExample.Criteria criteria = exportExample.createCriteria();
        //添加查询条件company_id
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        ArrayList<Long> list = new ArrayList<>();
        list.add(0l);
        list.add(1l);
        list.add(2l);
        criteria.andStateIn(list);
        PageInfo<Export> pageInfo = exportService.findByPage(exportExample, pageNum, pageSize);
        //保存查询结果
        request.setAttribute("pageInfo", pageInfo);
        //进入合同管理列表
        return "cargo/export/export-list";
    }

    @RequestMapping("/toExport")
    public String toExport(String id) {
        if (id == null || "".equals(id)) {
            return "redirect:/cargo/export/contractList";
        }
        String[] split = id.split(",");
        List<String> strings = Arrays.asList(split);
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        criteria.andIdIn(strings);
        List<Contract> list = contractService.findAll(example);
        String contractNo = "";
        for (int i = 0; i < list.size(); i++) {
            Contract contract = list.get(i);
            if (i == list.size() - 1) {
                contractNo += contract.getContractNo();
            } else {
                contractNo += contract.getContractNo() + ",";
            }
        }
        //存储合同号
        request.setAttribute("contractNo", contractNo);
        // 存储购销合同的id
        request.setAttribute("id", id);
        return "cargo/export/export-toExport";
    }

    //修改添加
    @RequestMapping("/edit")
    public String edit(Export export) {
        export.setCompanyId(getLoginCompanyId());
        export.setCompanyName(getLoginCompanyName());
        //判断
        if (StringUtils.isEmpty(export.getId())) {
            log.info("货运单添加...");
            //设置创建时间
            export.setCreateTime(new Date());
            exportService.save(export);
        } else {
            log.info("货运单修改...");
            exportService.update(export);
        }
        //添加成功，转发到报运单列表
        return "redirect:/cargo/export/list";
    }

    /**
     * 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {

        //1. 根据报运单的id查询报运单
        Export export = exportService.findById(id);

        //2. 根据报运单的id，查询报运单的所有商品
        ExportProductExample example = new ExportProductExample();
        // 查询条件：export_id
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProductList = exportProductService.findAll(example);

        //3. 保存
        request.setAttribute("export", export);
        request.setAttribute("eps", exportProductList);
        return "cargo/export/export-update";
    }


    /**
     * 出口报运单的提交取消
     */
    @RequestMapping("/submit")
    public String submit(String id) {
        // 创建报运单对象，修改状态为1，已上报状态
        Export export = new Export();
        export.setId(id);
        export.setState(1);
        // 修改，动态sql，对象属性有值才修改
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }

    @RequestMapping("/cancel")
    public String cancel(String id) {
        // 创建报运单对象，修改状态为0，草稿状态
        Export export = new Export();
        export.setId(id);
        export.setState(0);
        // 修改，
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }

    //电子报运:远程访问海关报运平台的webservice服务
    @RequestMapping("/exportE")
    public String exportE(String id) {
        //创建电子报运单对象
        ExportVo exportVo = new ExportVo();
        //从数据库查出运单信息并复制到报运单对象中去
        Export export = exportService.findById(id);
        BeanUtils.copyProperties(export, exportVo);
        // 【......设置报运单id.......】
        exportVo.setExportId(id);
        //获取报运单中报运货物集合
        List<ExportProductVo> products = exportVo.getProducts();
        //创建查询对象，根据ID来查找报运单下所有货物列表
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> productList = exportProductService.findAll(example);
        //所有货物到电子报运单中去
        if (productList != null && productList.size() > 0) {
            for (ExportProduct product : productList) {
                //创建电子报运单货物对象并copy运单下货物信息
                ExportProductVo exportProductVo = new ExportProductVo();
                BeanUtils.copyProperties(product, exportProductVo);
                // 【......设置报运单id.......】
                exportProductVo.setExportId(id);
                // 【......设置商品id.......】
                exportProductVo.setExportProductId(product.getId());
                //添加到集合
                products.add(exportProductVo);
            }
        }

        WebClient.create("http://127.0.0.1:8080/ws/export/user").post(exportVo);
        ExportResult exportResult = WebClient.create("http://127.0.0.1:8080/ws/export/user/" + id)
                .get(ExportResult.class);
        exportService.updateByExportResult(exportResult);
        return "redirect:/cargo/export/list";
    }

    @RequestMapping("/toView")
    public String toView(String id){
        //1. 根据报运单的id查询报运单
        Export export = exportService.findById(id);
        //2. 根据报运单的id，查询报运单的所有商品
        ExportProductExample example = new ExportProductExample();
        // 查询条件：export_id
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProductList = exportProductService.findAll(example);
        //3. 保存
        request.setAttribute("export", export);
        request.setAttribute("eps", exportProductList);
        return "cargo/export/export-view";
    }
}
